<template>
	<view class="container">
		<button class="select-btn" @click="handleSelectFile" :disabled="loading">
			{{ loading ? '处理中...' : '选择文件' }}
		</button>

		<view class="file-list">
			<view v-for="(item, index) in fileList" :key="index" class="file-info">
				<view class="info-item">
					<text class="label">文件名：</text>
					<text class="value">{{ item.name }}</text>
				</view>
				<view class="info-item">
					<text class="label">MD5值：</text>
					<text class="value md5">{{ item.md5 }}</text>
				</view>
			</view>
		</view>


		<view v-if="loading" class="loading">
			<text>正在计算MD5，请稍候...</text>
		</view>
	</view>
</template>

<script setup>
import {
	ref
} from 'vue'
import SparkMD5 from 'spark-md5'

const loading = ref(false)
const fileList = ref([])

const handleSelectFile = async () => {
	console.log('开始选择文件...')
	try {
		loading.value = true
		let files = []

		// 平台判断
		// #ifdef H5
		files = await selectFileH5()
		// #endif

		// #ifdef APP-PLUS
		files = await selectFileApp()
		// #endif

		if (!files || files.length === 0) {
			console.warn('[3] 未选择有效文件')
			return
		}

		// 处理每个文件
		for (const file of files) {
			console.log('[4] file', file)
			console.log('[4] 开始计算MD5...', file.name)
			const md5 = await calculateMd5(file)
			console.log('[5] MD5计算完成:', md5)

			fileList.value.push({
				name: file.name || file.path.split('/').pop(),
				md5: md5
			})
		}
	} catch (error) {
		console.error('[ERROR] 文件处理错误:', error)
		uni.showToast({
			title: error.message || '处理失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// APP端选择文件
const selectFileApp = () => {
	console.log('[DEBUG] 进入APP文件选择方法')
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 30,
			sizeType: ['original'],
			sourceType: ['album'],
			success: async function (res) {
				resolve(res.tempFiles)
			},
			fail: (error) => {
				console.error('选择文件失败:', error)
				reject(new Error('选择文件失败'))
			}
		})
	})
}

// H5端选择文件
const selectFileH5 = () => {
	return new Promise((resolve) => {
		const input = document.createElement('input')
		input.type = 'file'
		input.multiple = true
		input.onchange = (e) => {
			const files = Array.from(e.target.files)
			console.log('[H5] 选择文件结果:', files.map(f => ({
				name: f.name,
				size: f.size,
				type: f.type
			})))
			resolve(files)
		}
		input.click()
	})
}

// 计算MD5
const calculateMd5 = async (file) => {
	return new Promise((resolve, reject) => {
		// #ifdef H5
		const spark = new SparkMD5.ArrayBuffer()
		const reader = new FileReader()
		reader.readAsArrayBuffer(file)
		reader.onload = (e) => {
			spark.append(e.target.result)
			const md5 = spark.end()
			resolve(md5)
		}
		reader.onerror = (error) => {
			reject(new Error('文件读取失败'))
		}
		// #endif

		// #ifdef APP-PLUS
		plus.io.getFileInfo({
			filePath: file.path,
			digestAlgorithm: "md5",
			success: function (e) {
				resolve(e.digest)
			},
			fail: function (e) {
				reject(new Error('获取文件信息失败'))
			}
		})
		// #endif
	})
}
</script>

<style lang="scss" scoped>
.container {
	padding: 40rpx;
	min-height: 100vh;
	background-color: #f5f7fa;
}

.select-btn {
	background-color: #409eff;
	color: white;
	font-size: 32rpx;
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 12rpx;
	margin-bottom: 40rpx;

	&[disabled] {
		background-color: #a0cfff;
	}
}


.file-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.file-info {
	background: white;
	padding: 32rpx;
	border-radius: 12rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

	.info-item {
		margin-bottom: 24rpx;
		display: flex;
		align-items: center;

		.label {
			font-size: 28rpx;
			color: #606266;
			min-width: 120rpx;
		}

		.value {
			font-size: 28rpx;
			color: #303133;
			word-break: break-all;

			&.md5 {
				color: #67c23a;
				font-family: monospace;
			}
		}
	}
}

.loading {
	text-align: center;
	font-size: 28rpx;
	color: #909399;
	margin-top: 40rpx;
}
</style>